const mysql = require('./nestjs-app/node_modules/mysql2/promise');

// 测试1340指令：大小+赤壁累计赢金排行榜
async function test1340DiceAndChibiRankings() {
    let connection;
    try {
        connection = await mysql.createConnection({
            host: '43.143.253.188',
            user: 'nextjs',
            password: 'yEAiRE2jcxTyRBy5',
            database: 'nextjs'
        });
        console.log('✅ 数据库连接成功');

        // 1. 查询 casino_dice_bets 赢金
        const [diceRows] = await connection.execute(`
      SELECT userId, characterId, SUM(winAmount) as winGold
      FROM casino_dice_bets
      WHERE status = 2 AND winAmount > 0
      GROUP BY characterId, userId
    `);

        // 2. 查询 casino_chibi_bets 赢金
        const [chibiRows] = await connection.execute(`
      SELECT userId, characterId, SUM(winGold) as winGold
      FROM casino_chibi_bets
      WHERE status = 2 AND winGold > 0
      GROUP BY characterId, userId
    `);

        // 3. 合并两个表，按 characterId 累加总赢金
        const characterMap = new Map();
        function addWin(row) {
            if (!row.characterId) return;
            const key = row.characterId;
            if (!characterMap.has(key)) {
                characterMap.set(key, {
                    userId: row.userId,
                    characterId: row.characterId,
                    winGold: 0
                });
            }
            characterMap.get(key).winGold += parseInt(row.winGold || 0);
        }
        diceRows.forEach(addWin);
        chibiRows.forEach(addWin);

        // 4. 排序取前50
        const rankingArr = Array.from(characterMap.values())
            .sort((a, b) => b.winGold - a.winGold)
            .slice(0, 50);

        // 5. 查角色名
        const characterIds = rankingArr.map(r => r.characterId).filter((id, idx, arr) => id && arr.indexOf(id) === idx);
        let characterNameMap = {};
        if (characterIds.length > 0) {
            const [characters] = await connection.execute(
                `SELECT id, name FROM characters WHERE id IN (${characterIds.map(() => '?').join(',')})`,
                characterIds
            );
            characters.forEach(char => {
                characterNameMap[char.id] = char.name;
            });
        }

        // 6. 拼接称号，输出排行榜
        const list = rankingArr.map(row => {
            const totalWinAmount = row.winGold;
            let title = "赌徒";
            if (totalWinAmount >= 10000000) title = "赌神";
            else if (totalWinAmount >= 5000000) title = "赌圣";
            else if (totalWinAmount >= 1000000) title = "赌侠";
            else if (totalWinAmount >= 500000) title = "赌狂";
            else if (totalWinAmount >= 100000) title = "赌魔";
            else if (totalWinAmount >= 50000) title = "赌痴";
            else if (totalWinAmount >= 10000) title = "赌怪";
            else if (totalWinAmount >= 5000) title = "赌鬼";
            return {
                name: characterNameMap[row.characterId] || `角色${row.characterId}`,
                record: totalWinAmount,
                title,
                userid: row.userId
            };
        });

        // 7. 输出排行榜
        const mockResponse = {
            act_id: 1340,
            code: 0,
            list,
            type: 41
        };
        console.log('\n=== 1340累计赢金排行榜 ===');
        console.log(JSON.stringify(mockResponse, null, 2));
    } catch (error) {
        console.error('❌ 测试失败:', error);
    } finally {
        if (connection) {
            await connection.end();
            console.log('\n✅ 数据库连接已关闭');
        }
    }
}

test1340DiceAndChibiRankings().catch(console.error);
